package com.qhhc.controller;

import com.qhhc.entity.FileInfo;
import com.qhhc.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@Controller
public class FileController {

    private final FileService fileService;

    @Autowired
    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("files", fileService.getAllFiles());
        return "index";
    }

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "请选择要上传的文件");
            return "redirect:/";
        }

        try {
            FileInfo fileInfo = fileService.uploadFile(file);
            redirectAttributes.addFlashAttribute("message", "文件上传成功: " + fileInfo.getOriginalFileName());
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message", "文件上传失败: " + e.getMessage());
        }

        return "redirect:/";
    }

    @GetMapping("/download/{id}")
    public ResponseEntity<Resource> downloadFile(@PathVariable Long id) {
        FileInfo fileInfo = fileService.getFileById(id);
        if (fileInfo == null) {
            return ResponseEntity.notFound().build();
        }

        try {
            Path filePath = Paths.get(fileInfo.getFilePath());
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileInfo.getOriginalFileName() + "\"")
                        .contentType(MediaType.parseMediaType(fileInfo.getFileType()))
                        .body(resource);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            return ResponseEntity.badRequest().body(null);
        }
    }

    @PostMapping("/delete/{id}")
    public String deleteFile(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        boolean deleted = fileService.deleteFile(id);
        if (deleted) {
            redirectAttributes.addFlashAttribute("message", "文件删除成功");
        } else {
            redirectAttributes.addFlashAttribute("message", "文件删除失败");
        }
        return "redirect:/";
    }

    @GetMapping("/process/{id}")
    public String showProcessForm(@PathVariable Long id, Model model) {
        FileInfo fileInfo = fileService.getFileById(id);
        if (fileInfo == null) {
            return "redirect:/";
        }
        
        model.addAttribute("file", fileInfo);
        return "process";
    }

    @PostMapping("/process/{id}")
    public String processFile(@PathVariable Long id, 
                             @RequestParam("operation") String operation,
                             @RequestParam(value = "param", required = false) String param,
                             RedirectAttributes redirectAttributes) {
        try {
            FileInfo fileInfo = fileService.processFile(id, operation, param);
            if (fileInfo != null) {
                redirectAttributes.addFlashAttribute("message", "文件处理成功");
            } else {
                redirectAttributes.addFlashAttribute("message", "文件处理失败");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("message", "文件处理出错: " + e.getMessage());
        }
        
        return "redirect:/";
    }
    
    @ResponseBody
    @GetMapping("/api/files")
    public Map<String, Object> getFiles() {
        Map<String, Object> response = new HashMap<>();
        response.put("files", fileService.getAllFiles());
        return response;
    }

    @GetMapping("/api/files/{id}")
    @ResponseBody
    public FileInfo getFile(@PathVariable Long id) {
        return fileService.getFileById(id);
    }

    @GetMapping("/api/filesp")
    @ResponseBody
    public Map<String, Object> getFiles(@RequestParam(defaultValue = "0") int page,
                                        @RequestParam(defaultValue = "10") int size) {
        Map<String, Object> response = new HashMap<>();
        response.put("files", fileService.getFiles(page, size));
        response.put("total", fileService.getTotalFiles());
        return response;
    }
}